<?php
namespace app\api\controller;

use app\api\Controller;
use think\Db;


class Deposit extends Base
{
    public function user_deposit(){
        $data['deposit'] = Db::name('user')->where('id',$this->userId)->value('deposit');
        
        $this->success("请求成功!", $data);
    }
   //用户申请退款
    public function backDeposit(){
        $data['status'] = 0;

        $deposit_info  = Db::name('user')->where('id',$this->userId)->field('deposit,out_trade_no')->find();
        
        if($deposit_info['deposit'] > 0 && $deposit_info['out_trade_no']){
        	$out_trade_no = $deposit_info['out_trade_no'];
	           
            if($pay_info      = Db::name('charge_log')->where('out_trade_no',$out_trade_no)->field('deposit,amount')->find()){
                if($this->addDepositLog($out_trade_no,$pay_info)){
                    if($this->requestBackDeposit($out_trade_no,$pay_info)){
                       $data['status'] = $this->clearUserDepositInfo() ? 1 : 2;
                    }
                }
                Db::name('deposit_log')->where('out_trade_no',$out_trade_no)->update($data);
            }
		        
	        
        }

        
        $this->success("请求成功!", $data);
    }
    
    //插入用户退款日志
    private function addDepositLog($out_trade_no,$pay_info){
    	$insert_info['user_id']      = $this->userId;
	    $insert_info['deposit']      = $pay_info['deposit'];
	    $insert_info['out_trade_no'] = $out_trade_no;
	    $insert_info['create_time']  = time();
	    $insert_info['update_time']  = $insert_info['create_time']; 
         
        return Db::name('deposit_log')->insert($insert_info) ? true : false;
    }

 
    //清空用户表里用户的押金信息
    private function clearUserDepositInfo(){
    	$update_info['deposit'] = 0;
    	$update_info['out_trade_no'] = '';
    	return Db::name('user')->where('id',$this->userId)->update($update_info);
    }

    //请求微信退还用户的押金
    private function requestBackDeposit($out_trade_no,$pay_info){
    	$nonce_str     = getRandCode(16);//生成随机的32位字符串
        $out_refund_no = date('YmdHis',time()).getRandCode(6);//商户的订单号

        $total_fee = $pay_info['amount']*100;
        $deposit   = $pay_info['deposit']*100;
  
    	$prepay = array(
		            'appid'            => 'wxa641018b058e4ac9', //小程序qppid
		            'mch_id'           => '1326035601', 
		            'nonce_str'        => $nonce_str,//生成随机的32位字符串
		            'op_user_id'       => '1326035601',
		            'out_refund_no'    => $out_refund_no,
		            'out_trade_no'     => $out_trade_no,//商户的订单号
		            'refund_fee'       => $deposit,
		            'total_fee'        => $total_fee       
                  );
        
        $xml = "<xml>
                     <appid>wxa641018b058e4ac9</appid>
                     <mch_id>1326035601</mch_id>
                     <nonce_str>".$nonce_str."</nonce_str>
                     <op_user_id>1326035601</op_user_id>
                     <out_refund_no>".$out_refund_no."</out_refund_no>
                     <out_trade_no>".$out_trade_no."</out_trade_no>
                     <refund_fee>".$deposit."</refund_fee>
                     <total_fee>".$total_fee."</total_fee>
                     <sign>".$this->MakeSign($prepay)."</sign>
                 </xml>";
        //调用api，自定义对参数进行处理，改请求方式是自定义方式 
        $xml_result = curlRequest($xml);

        $result     = json_decode(json_encode(simplexml_load_string($xml_result, 'SimpleXMLElement', LIBXML_NOCDATA)),true);
    
        return $result['result_code'] == 'SUCCESS' ? true : false;
       
    }

    private function MakeSign($prepay){
        //签名步骤一：按字典序排序参数
        ksort($prepay);
        $string = $this->ToUrlParams($prepay);
        //签名步骤二：在string后加入KEY
        $string = $string . "&key=d57f65ebb69106cd68d1aacd7b8616d7";
        //签名步骤三：MD5加密
        $string = md5($string);
        //签名步骤四：所有字符转为大写
        $result = strtoupper($string);
        return $result;
    }

    /**
     * 格式化参数格式化成url参数
     */
    private function ToUrlParams($prepay)
    {
        $buff = "";
        foreach ($prepay as $k => $v)
        {
            if($k != "sign" && $v != "" && !is_array($v)){
                $buff .= $k . "=" . $v . "&";
            }
        }

        $buff = trim($buff, "&");
        return $buff;
    }

}